# coding:utf8
import Queue
import datetime
import json
import thread
import time

import requests

from BashouScrapy.wenshu.common import SpiderConf

proxy_queue = Queue.Queue()
socks_proxy_queue = Queue.Queue()
proxy_queue_lock = thread.allocate_lock()
socks_proxy_queue_lock = thread.allocate_lock()


def init_proxy(thread_local_data):
    print ('init_proxy')
    if SpiderConf.use_proxy is not True:
        thread_local_data.proxy = None
        return
    try:
        if thread_local_data.proxy is not None:
            return
    except Exception:
        pass

    proxy_queue_lock.acquire()
    while proxy_queue.empty():
        url = 'http://proxy.mimvp.com/api/fetch.php?orderid=860170831103115351&num=50&anonymous=5&ping_time=1&result_fields=1,2,3,4,5,6,7,9&result_format=json&country=%E4%B8%AD%E5%9B%BD'
        r = requests.get(url)
        ip_ports = json.loads(r.text)
        print (ip_ports)
        for obj in ip_ports['result']:
            proxy_queue.put(obj)
    proxy_queue_lock.release()
    proxy_obj = proxy_queue.get()
    http_type = proxy_obj['http_type'].lower()
    http_type_value = None
    if http_type.find('https') != -1:
        http_type_value = 'https'
    elif http_type.find('http') != -1:
        http_type_value = 'http'
    elif http_type.find('socks4') != -1:
        http_type_value = 'socks4'
    elif http_type.find('socks5') != -1:
        http_type_value = 'socks5'
    proxies = {
        http_type_value: proxy_obj["ip:port"]
    }
    thread_local_data.proxy = proxies
    thread_local_data.proxy_str = http_type_value + '://' + proxy_obj["ip:port"]


def init_socks_proxy(thread_local_data):
    print ('init_socks_proxy')
    if SpiderConf.use_proxy is not True:
        thread_local_data.socks_proxy_str = None
        return
    try:
        if thread_local_data.socks_proxy_str is not None:
            return
    except Exception:
        pass

    socks_proxy_queue_lock.acquire()
    while socks_proxy_queue.empty():
        time.sleep(2)
        url = 'http://proxy.mimvp.com/api/fetch.php?orderid=860170831103115351&num=20&anonymous=3,4,5&http_type=4,5,6&ping_time=1&isp=1,2,3,4,5,6,7,8,13&result_fields=1,2,3,4,5,6,7,9&result_sort_field=2&result_format=json&country=%E4%B8%AD%E5%9B%BD'
        r = requests.get(url)
        ip_ports = json.loads(r.text)
        print (ip_ports)
        for obj in ip_ports['result']:
            http_type = obj["http_type"].lower()
            if http_type == "socks4" or http_type == "socks5" or http_type == "socks4/socks5":
                socks_proxy_queue.put(obj)
    socks_proxy_queue_lock.release()
    proxy_obj = socks_proxy_queue.get()
    http_type = proxy_obj['http_type'].lower()
    http_type_value = None
    if http_type.find('socks4') != -1:
        http_type_value = 'socks4'
    elif http_type.find('socks5') != -1:
        http_type_value = 'socks5'
    thread_local_data.socks_proxy_str = http_type_value + '://' + proxy_obj["ip:port"]
    print ("socks:" + str(datetime.datetime.now()) + thread_local_data.socks_proxy_str)


# def init_proxy():
#     if SpiderConf.use_proxy is not True:
#         return
#     try:
#         thread_local_data.proxy
#         requests.get('http://' + SpiderConf.proxy_pool_server + '/delete?ip=' + thread_local_data.proxy_ip)
#     except Exception:
#         pass
#
#     proxy_queue_lock.acquire()
#     while proxy_queue.empty():
#         url = 'http://' + SpiderConf.proxy_pool_server + '/?count=30'
#         r = requests.get(url)
#         ip_ports = json.loads(r.text)
#         print ip_ports
#         for obj in ip_ports:
#             proxy_queue.put(obj)
#     proxy_queue_lock.release()
#     ip_port = proxy_queue.get()
#     ip = ip_port[0]
#     port = ip_port[1]
#     proxies = {
#         'http': 'http://%s:%s' % (ip, port),
#         'https': 'http://%s:%s' % (ip, port)
#     }
#     thread_local_data.proxy = proxies
#     thread_local_data.proxy_str = 'http://%s:%s' % (ip, port)
#     thread_local_data.proxy_ip = ip


# def delete_and_update_proxy(proxy):
#     # 更换代理 ---> 把当前获取的这个代理置为无效
#     MaYiPorxyPool.delete_unavailable_proxy(proxy)
#     print "线程" + str(threading.currentThread()) + "删除无用代理" + str(proxy)
#     # 查询有效的代理数小于规定数量之后，再去蚂蚁代理申请一个，插入到数据库
#     available_proxy = MaYiPorxyPool.get_avaliable_proxy()
#     available_count = available_proxy.count()
#     # 防止代理表有时候为空的情况，每次插入保证有4条
#     if available_count < 8:
#         for i in range(8 - available_count):
#             result = insert_proxy()
#             if result != False:
#                 print "线程" + str(threading.currentThread()) + "新增" + str(i + 1) + "个代理成功"

def change_socks_proxy(thread_local_data):
    print ('change_socks_proxy')
    thread_local_data.socks_proxy_str = None
    init_socks_proxy(thread_local_data)


def change_proxy(thread_local_data):
    print ('change_proxy')
    thread_local_data.proxy = None
    init_proxy(thread_local_data)
